package top.lucky.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author miaojingyun
 * @date 2022/2/14, 11:40
 */
@Slf4j
public class UrlUtil {

    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @throws IOException
     */
    public static byte[] getUrlInputStream(String urlStr) throws IOException {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(20 * 1000);
            conn.setRequestMethod("GET");
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            return IOUtils.toByteArray(conn.getInputStream());
        } catch (Exception e) {
            log.error("failed to get inputStream from Url " + urlStr, e);
            throw new IOException("failed to get inputStream from Url " + urlStr);
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
            }
        }
    }


}
